package com.studor.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.studor.dto.LoginRequest;
import com.studor.dto.LoginResponse;
import com.studor.dto.UserCreateRequest;
import com.studor.dto.UserUpdateRequest;
import com.studor.entity.Account;
import com.studor.entity.Student;
import com.studor.mapper.AccountMapper;
import com.studor.service.AccountService;
import com.studor.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements AccountService {

    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    
    @Autowired
    private StudentService studentService;

    @Override
    public LoginResponse login(LoginRequest request) {
        Account account = getAccountByUsername(request.getUsername());

        if (account == null) {
            throw new RuntimeException("用户不存在");
        }

        if (!passwordEncoder.matches(request.getPassword(), account.getPassword())) {
            throw new RuntimeException("密码错误");
        }

        // 登录成功，生成token
        StpUtil.login(account.getId());
        String token = StpUtil.getTokenValue();

        return new LoginResponse(token, account.getId(), account.getUsername(),
                               account.getEmail(), account.getRole());
    }

    @Override
    public Account getAccountByUsername(String username) {
        QueryWrapper<Account> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        return this.getOne(wrapper);
    }
    
    @Override
    @Transactional
    public Account createUser(UserCreateRequest request) {
        // 检查用户名是否已存在
        if (getAccountByUsername(request.getUsername()) != null) {
            throw new RuntimeException("用户名已存在");
        }
        
        // 创建账户
        Account account = new Account();
        account.setUsername(request.getUsername());
        account.setPassword(passwordEncoder.encode(request.getPassword()));
        account.setEmail(request.getEmail());
        account.setRole(request.getRole());
        account.setRegisterTime(LocalDateTime.now());
        
        this.save(account);
        
        // 如果是学生角色，创建学生信息
        if ("stu".equals(request.getRole())) {
            Student student = new Student();
            student.setId(account.getId());
            student.setName(request.getName());
            student.setGender(request.getGender());
            student.setMajor(request.getMajor());
            student.setTele(request.getTele());
            student.setInf(request.getInf());
            studentService.save(student);
        }
        
        return account;
    }
    
    @Override
    @Transactional
    public Account updateUser(UserUpdateRequest request) {
        Account account = this.getById(request.getId());
        if (account == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 检查用户名是否被其他用户使用
        Account existingAccount = getAccountByUsername(request.getUsername());
        if (existingAccount != null && !existingAccount.getId().equals(request.getId())) {
            throw new RuntimeException("用户名已被使用");
        }
        
        // 更新账户信息
        account.setUsername(request.getUsername());
        account.setEmail(request.getEmail());
        account.setRole(request.getRole());
        
        // 如果提供了新密码，更新密码
        if (request.getNewPassword() != null && !request.getNewPassword().trim().isEmpty()) {
            account.setPassword(passwordEncoder.encode(request.getNewPassword()));
        }
        
        this.updateById(account);
        
        // 如果是学生角色，更新学生信息
        if ("stu".equals(request.getRole())) {
            Student student = studentService.getById(request.getId());
            if (student == null) {
                student = new Student();
                student.setId(request.getId());
            }
            student.setName(request.getName());
            student.setGender(request.getGender());
            student.setMajor(request.getMajor());
            student.setTele(request.getTele());
            student.setInf(request.getInf());
            studentService.saveOrUpdate(student);
        }
        
        return account;
    }
    
    @Override
    @Transactional
    public void deleteUser(Integer id) {
        Account account = this.getById(id);
        if (account == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 删除学生信息（如果存在）
        if ("stu".equals(account.getRole())) {
            studentService.removeById(id);
        }
        
        // 删除账户
        this.removeById(id);
    }
}
